<template>
  <div class="content">

    <el-form ref="form" :model="form"  label-width="120px" :inline="true">

      <el-form-item label="请选择用户类型:">
        <el-radio-group v-model="form.userType" @change="changeType">
          <el-radio label="1" >学生</el-radio>
          <el-radio label="2">教职工</el-radio>
        </el-radio-group>
      </el-form-item>

      <br/>

      <el-form-item prop="userName" >
        <el-input v-model="form.userName"  size="mini" placeholder="姓名"></el-input>
      </el-form-item>

      <el-form-item prop="idCard">
        <el-input v-model="form.idCard"  size="mini"  placeholder="身份证号"></el-input>
      </el-form-item>
      <el-form-item prop="deptId">
      <el-select
        clearable
        v-model="form.deptId"
        @change="gradeList(form.deptId)"
        placeholder="请选择所属学校"
        size="mini"
      >
        <el-option :label="item.name" :value="item.id" v-for="item in schoolList" :key="item.id"></el-option>
      </el-select>
      </el-form-item>
      <el-form-item prop="glassId">
        <el-select
          clearable
          v-model="form.glassId"
          @change="classList(form.glassId)"
          placeholder="请选择年级"
          size="mini"
          style="width:150px"
        >
          <el-option
            :label="item.name"
            :value="item.id"
            v-for="(item,index) in gradeData"
            :key="index"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item prop="classId">
        <el-select clearable v-model="form.classId" placeholder="请选择班级" size="mini" style="width:150px">
          <el-option
            :label="item.name"
            :value="item.id"
            v-for="(item,index) in classData"
            :key="index"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item prop="startTime">
      <el-date-picker
        v-model="form.startTime"
        type="datetime"
        size="mini"
        :default-value="new Date()"
        value-format="yyyy-MM-dd HH:mm:ss"
        style="margin-right: 10px;width: 170px;"
        placeholder="选择开始日期">
      </el-date-picker>
      </el-form-item>

      <el-form-item prop="endTime">
      <el-date-picker
        v-model="form.endTime"
        type="datetime"
        :default-value="new Date()"
        value-format="yyyy-MM-dd HH:mm:ss"
        size="mini"
        style="margin-right: 10px;width: 170px!important;"
        placeholder="选择结束日期">
      </el-date-picker>
      </el-form-item>
      <el-form-item>
      <el-button type="primary" size="mini" class="btn" @click="search">查询</el-button>
      <el-button type="primary" size="mini" class="btn" @click="resetForm('form')">重置</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" @click="dialogTableVisible = true">充值</el-button></el-form-item>
        <el-form-item>
        <el-upload
          class="upload"
          :action="url+'/admin/offlineRechare/upload'"
          :on-success="uploadSuccess"
          :headers="requestHeader"
          :limit="100"
          accept="xlsx"
          :show-file-list="false"
          :on-exceed="handleExceed"
        >
          <el-button size="mini" type="primary" style="margin-right:10px"><i class="fa fa-arrow-up" style="margin-right:5px;"></i>批量充值</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item>
      <el-button type="primary" size="mini" @click="excelExport">导出</el-button>
      </el-form-item>
    </el-form>
    <el-dialog title="充值" :visible.sync="dialogTableVisible" width="30%">
      <el-form :model="ruleForm" status-icon  ref="ruleForm" label-width="120px" class="demo-ruleForm">
        <el-form-item label="学校" prop="deptId">
          <el-select
            clearable
            v-model="ruleForm.deptId"
            @change="gradeList(ruleForm.deptId)"
            placeholder="请选择所属学校"
            size="mini"
          >
            <el-option :label="item.name" :value="item.id" v-for="item in schoolList" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年级" v-if="form.userType==1" prop="glassId">
          <el-select
            clearable
            v-model="ruleForm.glassId"
            @change="classList(ruleForm.glassId)"
            placeholder="请选择年级"
            size="mini"
            style="width:150px"
          >
            <el-option
              :label="item.name"
              :value="item.id"
              v-for="(item,index) in gradeData"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="班级" v-if="form.userType==1"  prop="classId">
          <el-select clearable
                     v-model="ruleForm.classId"
                     @change="studentList(ruleForm.classId)"
                     placeholder="请选择班级"
                     size="mini" style="width:150px">
            <el-option
              :label="item.name"
              :value="item.id"
              v-for="(item,index) in classData"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="姓名" prop="userName">
          <el-autocomplete
            class="inline-input"
            size="mini"
            v-model="ruleForm.userName"
            :fetch-suggestions="querySearch"
            placeholder="请输入内容"
            @select="handleSelect"
          ></el-autocomplete>
        </el-form-item>

        <el-form-item label="身份证号" prop="idCard">
          <el-input type="primary" disabled size="mini" v-model="ruleForm.idCard" autocomplete="off"></el-input>
        </el-form-item>


        <el-form-item label="充值金额" prop="payamount">
          <el-input type="number" size="mini"  v-model="ruleForm.payamount" autocomplete="off">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>

        <el-form-item label="缴费渠道" prop="channal">
          <el-radio-group v-model="ruleForm.channal">
            <div style="margin-top: 10px">
              <el-radio label="现金支付"></el-radio>
              <el-radio label="银联支付"></el-radio>

            </div>
            <div style="margin-top: 10px;margin-bottom: 20px;font-size: 14px">
              <el-radio label="微信支付"></el-radio>
              <el-radio label="支付宝支付"></el-radio>
            </div>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="余额" prop="bal">
          <el-input type="number"  disabled  size="mini"  v-model="ruleForm.bal" autocomplete="off">
          </el-input>
        </el-form-item>
        <div style="margin: 10px;padding-left: 100px">
          <el-button type="primary" size="mini" @click="open" >充值</el-button>
          <el-button type="primary" size="mini" @click="dialogTableVisible = false" >取消</el-button>
        </div>
      </el-form>
    </el-dialog>
    <el-dialog
      title="充值信息确认"
      :visible.sync="dialogVisible"
      width="20%">
      <el-row :gutter="0">
        <el-col :span="10">学生姓名</el-col>
        <el-col :span="14" style="text-align: right">{{ruleForm.userName}}</el-col>
        </el-row>
        <el-row :gutter="0">
        <el-col :span="10">身份证号</el-col>
        <el-col :span="14" style="text-align: right">{{ruleForm.idCard}}</el-col>
        </el-row>
      <el-row :gutter="0">
        <el-col :span="10">充值金额</el-col>
        <el-col :span="14" style="text-align: right;">{{ruleForm.payamount}}</el-col>
      </el-row>
      <el-row :gutter="0">
        <el-col :span="10">充值渠道</el-col>
        <el-col :span="14" style="text-align: right">{{ruleForm.channal}}</el-col>
      </el-row>
      <el-row :gutter="0">
        <el-col :span="10">账户余额</el-col>
        <el-col :span="14" style="text-align: right">{{ruleForm.bal}}</el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
    <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
    <el-button size="mini" type="primary" @click="recharge">确 定</el-button>
  </span>
    </el-dialog>
    <!-- <el-divider></el-divider> -->

    <template>
      <el-table
        :data="tableData"
        height="470"
        v-loading="loading"
        size="mini"
        style="width: 100%">
        <el-table-column
          prop="id"
          fixed
          label="ID"
          width="80">
        </el-table-column>

        <el-table-column
          prop="userName"
          width="120"
          label="姓名">
        </el-table-column>

        <el-table-column
          prop="idCard"
          width="160"
          label="身份证号">
        </el-table-column>

        <el-table-column
          prop="id"
          width="80"
          label="用户类型">
          <template slot-scope="scope">
            <span>{{scope.row.userType==1?'学生':'老师'}}</span>
          </template>
        </el-table-column>

        <el-table-column
          prop="paymentAmt"
          width="100"
          label="充值金额">
        </el-table-column>

        <el-table-column
          v-if="form.userType==1"
          prop="grade"
          width="80"
          label="年级">
        </el-table-column>

        <el-table-column
          v-if="form.userType==1"
          prop="classd"
          width="80"
          label="班级">
        </el-table-column>

        <el-table-column
          prop="channel"
          width="100"
          label="缴费渠道">
        </el-table-column>

        <el-table-column
          prop="finishTime"
          width="160"
          label="充值时间">
        </el-table-column>

        <el-table-column
          prop="optionUser"
          width="120"
          label="操作人">
        </el-table-column>

        <el-table-column
          prop="createTime"
          width="160"
          label="操作时间">
        </el-table-column>
        <el-table-column
          prop="status"
          width="160"
          label="充值状态">
          <template slot-scope="scope">
            <span style="color: #00ab63">{{scope.row.status}}</span>
          </template>
        </el-table-column>

      </el-table>
    </template>
    <el-row>
      <el-col :span="24">
        <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :page-sizes="[10, 15, 20,50,100]"
              :page-size="everyPageNum"
              layout="total, sizes,prev, pager, next, jumper"
              :total="total"
            ></el-pagination>
        <div class="grid-content bg-purple-dark" style="font-size:13px;float:right;margin:26px 0 0 10px">合计金额：<span style="color:rgb(20, 136, 154);font-weight:bold">{{sumData}}</span></div>
      </el-col>
    </el-row>
    <!--新增编辑弹框-->
    <el-dialog title="创建学生信息" :visible.sync="showEdit" width="40%" v-dialogDrag>
      <editStudent @hideEdit="hideEditStatus" ref="child" :msg="updateStatus"></editStudent>
    </el-dialog>
  </div>


</template>

<script>
    import Cookies from "js-cookie"
    import editStudent from "@/components/StudentManagement/edit";

    export default {
        name: "OfflineManagement",
        components: {
            editStudent
        },
        data() {
            return {

              dialogVisible:false,
              restaurants: [],
              dialogTableVisible:false,
                sumData: '',
                url:this.$Config.url,
                showEdit: false,//显示编辑弹框
                updateStatus:1,//默认是新增
                loading:false,
                total:1,//总页数
                everyPageNum:10,//每页多少条
                currentPage:1,//当前页
                form: {
                  userName:'',
                  startTime:'',
                  endTime:'',
                  idCard:'',
                  userType:'1',
                  glassId: "",
                  classId: "",
                  deptId: ""
                },
              ruleForm: {
                userName:'',
                idCard:'',
                userType:'1',
                glassId: "",
                classId: "",
                deptId: "",
                channal:"现金支付",
                payamount:0,
                bal:0,
                id:null
              },
              tableData: [],
              gradeData: [], //年级列表
              classData: [], //班级列表
              schoolList: [], //学校数据
              requestHeader: {
                "x-baie-admin-token": Cookies.get("token")
              },
            }
        },
        mounted() {
             this.common();
          this.getSchool();
          const userInfo = JSON.parse(localStorage.getItem("userInfo")).deptId;
          this.gradeList(userInfo);
        },
        methods: {

          recharge(){
            const that = this;
            this.$axios
              .get(that.url + "/admin/offlineRechare/oc", {
                params: {
                  userType:that.form.userType,
                  userId : that.ruleForm.id,
                  userName:that.ruleForm.userName,
                  idCard:that.ruleForm.idCard,
                  payAmount:that.ruleForm.payamount,
                  channal:that.ruleForm.channal
                },
                headers: {
                  "x-baie-admin-token": Cookies.get("token")
                }
              })
              .then(function(res) {
                if (res.data.code == 200) {
                  that.dialogVisible = false;
                  that.dialogTableVisible =false
                  that.$refs['ruleForm'].resetFields();
                  that.$message({
                    message: '充值成功',
                    type: "success"
                  });
                  that.common(that.currentPage,that.everyPageNum);
                } else {
                  that.$message({
                    message: res.data.msg,
                    type: "warning"
                  });
                }
              })
              .catch(function(error) {
                console.log(error);
              });
          },
          handleExceed(files, fileList) {
            this.$message.warning(
              `当前限制选择 3 个文件，本次选择了 ${
                files.length
              } 个文件，共选择了 ${files.length + fileList.length} 个文件`
            );
          },
          uploadSuccess(response, file, fileList) {
            if (response.code == 200) {
              this.$message({
                message: "导入成功",
                type: "success"
              });
              this.common(this.currentPage, this.everyPageNum);
            } else {
              this.$message({
                message: response.msg,
                type: "error"
              });
            }
          },
          open() {
            const that = this;

            if (that.ruleForm.classId.length <1 && that.form.userType=='1'){
              this.$alert('请选择班级', '提示', {
                confirmButtonText: '确定',
                callback: action => {
                  this.$message({
                    type: 'info',
                    message: '请选择班级'
                  });
                }
              });
              return;
            }
            if (that.ruleForm.userName.length <1){
              this.$alert('请选择姓名', '提示', {
                confirmButtonText: '确定',
                callback: action => {
                  this.$message({
                    type: 'info',
                    message: '请选择姓名'
                  });
                }
              });
              return;
            }
            if (that.ruleForm.payamount&&/^\d*?.(\d{1}|\d{2})$/.test(that.ruleForm.payamount)){
              this.dialogVisible = true
            }else {

              this.$alert('充值金额必须大于0', '提示', {
                confirmButtonText: '确定',
                callback: action => {
                  this.$message({
                    type: 'info',
                    message: '充值金额必须大于0'
                  });
                }
              });
              return
            }

          },
          handleSelect(item) {
            const that = this;
            that.ruleForm.bal = item.bal;
            that.ruleForm.idCard = item.idCard;
            that.ruleForm.id = item.id;
          },
          querySearch(queryString, cb) {
            var restaurants = this.restaurants;
            var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
            // 调用 callback 返回建议列表的数据
            cb(results);
          },
          createFilter(queryString) {
            return (restaurant) => {
              return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
            };
          },
          studentList(id){
            const that = this;
            this.$axios
              .get(that.url + "/admin/student/byClassId", {
                params: {
                  classId: id
                },
                headers: {
                  "x-baie-admin-token": Cookies.get("token")
                }
              })
              .then(function(res) {
                if (res.data.code == 200) {
                  that.restaurants = res.data.data;
                } else {
                  that.$message({
                    message: res.data.msg,
                    type: "warning"
                  });
                }
              })
              .catch(function(error) {
                console.log(error);
              });
          },
          classList(id) {
            const that = this;
            that.form.classId = "";
            this.$axios
              .get(that.url + "/admin/class/list", {
                params: {
                  gradeId: id
                },
                headers: {
                  "x-baie-admin-token": Cookies.get("token")
                }
              })
              .then(function(res) {
                if (res.data.code == 200) {
                  that.classData = res.data.data;
                } else {
                  that.$message({
                    message: res.data.msg,
                    type: "warning"
                  });
                }
              })
              .catch(function(error) {
                console.log(error);
              });
          },
          getSchool() {
            const that = this;
            this.$axios
              .get(that.url + "/admin/dept/list", {
                headers: {
                  "x-baie-admin-token": Cookies.get("token")
                }
              })
              .then(function(res) {
                if (res.data.code == 200) {
                  that.schoolList = res.data.data;
                } else {
                  that.$message({
                    message: res.data.msg,
                    type: "warning"
                  });
                }
              })
              .catch(function(error) {
                console.log(error);
              });
          },
          gradeList(id) {

            const that = this;

            if (that.dialogTableVisible == true && that.form.userType == '2'){
              that.ruleForm.idCard = '';
              this.$axios
                .get(that.url + "/admin/teacher/page", {
                  params: {
                    deptId: id,
                    pageNo:1,
                    pageSize:1000
                  },
                  headers: {
                    "x-baie-admin-token": Cookies.get("token")
                  }
                })
                .then(function(res) {
                  if (res.data.code == 200) {
                    let data = [... res.data.data.records];
                    data.map(e=>{
                      e.value=e.name
                      e.bal = e.balance
                      e.idCard = e.idNo
                      return e;
                    })

                    that.restaurants = data
                  } else {
                    that.$message({
                      message: res.data.msg,
                      type: "warning"
                    });
                  }
                })
                .catch(function(error) {
                  console.log(error);
                });
            }

            that.ruleForm.idCard = '';
            this.$axios
              .get(that.url + "/admin/grade/list", {
                params: {
                  deptId: id
                },
                headers: {
                  "x-baie-admin-token": Cookies.get("token")
                }
              })
              .then(function(res) {
                if (res.data.code == 200) {
                  that.gradeData = res.data.data;
                } else {
                  that.$message({
                    message: res.data.msg,
                    type: "warning"
                  });
                }
              })
              .catch(function(error) {
                console.log(error);
              });
          },
          resetForm(formName) {
            this.$refs[formName].resetFields();
          },
            excelExport() {
              const deptId = JSON.parse(localStorage.getItem("userInfo")).deptId;
                var divFrame = window.parent.document.getElementById(
                  "downLoadListFrame"
                );
                //判断是否存在，如果存在先移除，再重新创建
                if (divFrame != null) {
                  window.parent.document.body.removeChild(divFrame);
                }
                var iframe = window.parent.document.createElement("iframe");
                iframe.setAttribute("id", "downLoadListFrame");
                //download_file.id = "downFrame";
                window.parent.document.body.appendChild(iframe);
                divFrame = window.parent.document.getElementById("downLoadListFrame");
                //隐式调用，（注意：window.parent.document 适应对于，farme内部代码，调用frame 外部dom；如果项目未用frame，改写成 document即可）
                divFrame.src = `${this.url}/admin/offlineRechare/offlineExport?userType=${this.form.userType}&idCard=${this.form.idCard}&userName=${this.form.userName}&deptId=${this.form.deptId}&glassId=${this.form.glassId}&classId=${this.form.classId}&startTime=${this.form.startTime}&endTime=${this.form.endTime}`;
                divFrame.style.display = "none";
            },
            search(){
                this.common(this.currentPage,this.everyPageNum);
            },
            changeType(){
                this.$forceUpdate()
                this.common(this.currentPage,this.everyPageNum,this.form.userType);
            },
            handleSizeChange(val) {
                //   每页多少条
                this.everyPageNum=val;
                this.common(this.currentPage,val);
            },
            handleCurrentChange(val) {
                this.currentPage=val;
                this.common(val,this.everyPageNum);
            },
            hideEditStatus(status){
                this.showEdit=false;
                this.common(this.currentPage,this.everyPageNum);
            },
            common(pageNo=1,pageSize=10,userType=1) {
                const that = this;
                that.loading=true;
                let data={
                    pageNo,
                    pageSize,
                    userType:this.form.userType,
                }
                let dataStatus={};
                if(that.form.idCard){dataStatus.idCard=that.form.idCard};
                if(that.form.userName){dataStatus.userName=that.form.userName};
                if(that.form.deptId){dataStatus.deptId=that.form.deptId};
                if(that.form.gradeId){dataStatus.gradeId=that.form.gradeId};
                if(that.form.classId){dataStatus.classId=that.form.classId};
                if(that.form.startTime){dataStatus.startTime=that.form.startTime};
                if(that.form.endTime){dataStatus.endTime=that.form.endTime};

                let requestData={...data,...dataStatus}
                this.$axios.get(that.url+'/admin/offlineRechare/page', {
                    params:requestData,
                    headers: {
                        "x-baie-admin-token": Cookies.get("token")
                    }
                })
                    .then(function (res) {
                        that.loading=false;
                        if(res.data.code==200){
                            that.tableData = res.data.data.records;
                            that.total=res.data.data.total;
                            that.sumData = res.data.sum;
                        }else{
                            that.$message({
                                message: res.data.msg,
                                type: 'warning'
                            });
                        }

                    })
                    .catch(function (error) {
                        that.loading=false;
                        console.log(error);
                    });

            }
        }
    }
</script>

<style scoped lang="scss">
  .el-select,.el-input,.el-date-picker{
    width: 180px!important;
  }
  .el-range-editor--mini.el-input__inner{
    margin-top: 7px;
    margin-right: 10px;
    width: 300px;
  }
  .el-pagination{
    float: right;
    margin: 20px 10px;
  }
  .button_list {
    margin-bottom: 10px;
  }

  .content {
    text-align: left;
  }

  .el-divider {
    margin: 10px 0;
  }

  .btn {
    margin-top: 6px;
  }

  .el-form-item {
    margin-bottom: 0;
  }
</style>
